<?php

class UsersController extends AdminController
{
  public function init()
  {
    Yii::app()->user->loginUrl = '/admin/site/login';
  }

  /**
   * @return array action filters
   */
  public function filters()
  {
    return array(
        'accessControl', // perform access control for CRUD operations
    );
  }

  /**
   * Specifies the access control rules.
   * This method is used by the 'accessControl' filter.
   * @return array access control rules
   */
  public function accessRules()
  {
    return array(
        array('allow', // allow all users to perform 'index' and 'view' actions
            'actions' => array('list', 'setting', 'delete', 'select'),
            'roles' => array('member'),
        ),
        array('deny', // deny all users
            'users' => array('*'),
        ),
    );
  }


  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model=new Users;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Users']))
    {
      $model->attributes=$_POST['Users'];
      if($model->save())
        $this->redirect(array('view','id'=>$model->user_id));
    }

    $this->render('create',array(
        'model'=>$model,
    ));
  }

  public function actionSetting()
  {
    if (isset($_POST['command']) || isset($_POST['settingswitch'])) {
      $userSelected = Yii::app()->user->getState("userSelected", null);

      if ($userSelected && sizeof($userSelected)) {
        $usersDao = new UsersDAO();
        $usersDao->update(implode(',', $userSelected), $_POST['command'], $_POST['settingswitch']);

        Yii::app()->user->setFlash('success', Yii::t('main', 'users.update_success'));
      }

      Yii::app()->user->setState("userSelected", null);
      $this->redirect(array('list') + $_GET);
    }

  }

  public function actionDelete($id)
  {
    $model = $this->loadModel($id);
    $userDao = new UsersDAO();
    $userDao->delete($model->mobile, $model->serial_num);

    if (!isset($_GET['ajax'])) {
      Yii::app()->user->setFlash('success', Yii::t('main', 'users.delete_success'));
      $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('list'));
    }
  }

  public function actionSelect() {
    $ids = Yii::app()->request->getPost('ids');
    $isSelect = Yii::app()->request->getPost('isSelect');

    if ($ids) {
      $ids = explode(',', $ids);
      $useSelected = array();

      if (Yii::app()->user->hasState("userSelected")) {
        $useSelected = Yii::app()->user->getState("userSelected");
      }

      if ($ids) {
        foreach ($ids as $ind => $userId) {
          $userId = intval($userId);

          if ($isSelect == 'true') {
            $useSelected[$userId] = $userId;
          } else {
            unset($useSelected[$userId]);
          }
        }
      }

      Yii::app()->user->setState("userSelected", $useSelected);
      $this->_sendAjaxResponse(json_encode(array('status' => 1, 'count' => sizeof($useSelected))));
    }

    $this->_sendAjaxResponse(json_encode(array('status' => 1, 'count' => 0)));
  }
  /**
   * Lists all models.
   */
  public function actionList()
  {
    $criteria = new CDbCriteria();

    $criteria->addCondition('delete_flag=:delete_flag', 'AND');
    $params = array(':delete_flag' => Constants::DELETE_FLAG_FALSE);
    $searchData = array();

    if (isset($_GET['Users']) && sizeof($_GET['Users']) > 0) {
      $searchData = $_GET['Users'];

      foreach ($searchData as $key => $val) {
        if ($val != '') {
          $param = ':' . $key;
          $condtion = '';

          if ($key != 'create_date') {
            $condtion = $key . ' LIKE :' . $key . '';
            $params[$param] = '%' . $val . '%';
          } else {
            $condtion = $key . ' = :' . $key . '';
            $params[$param] = $val;
          }

          $criteria->addCondition($condtion, 'AND');
        }
      }
    }

    $criteria->params = $params;
    $count = Users::model()->count($criteria);

    $pages = new CPagination($count);

    // results per page
    $pages->pageSize = Constants::RECORD_OF_PAGE;
    $pages->applyLimit($criteria);

    $criteria->order = 'user_id DESC';
    $sort = new ExtSort('Users');
    $sort->applyOrder($criteria);

    $models = Users::model()->findAll($criteria);
    $searchModel=new Users('search');

    $userSelected = Yii::app()->user->getState("userSelected");

    $this->render('list', array('models' => $models, 'pages' => $pages, 'sort' => $sort, 'searchModel' => $searchModel, 'searchData' => $searchData, 'selected' => $userSelected));
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    $model=new Users('search');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['Users']))
      $model->attributes=$_GET['Users'];

    $this->render('admin',array(
        'model'=>$model,
    ));
  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer $id the ID of the model to be loaded
   * @return Users the loaded model
   * @throws CHttpException
   */
  public function loadModel($id)
  {
    $model=Users::model()->findByPk($id);
    if($model===null)
      throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  /**
   * Performs the AJAX validation.
   * @param Users $model the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}
